class LoginController < ApplicationController
  before_filter :authorize, :except => [:login,:register]
  
  layout "admin"


  
  def login
      session[:user_id] = nil

    if request.post?
			  if params[:openid_url]
			      puts "enter into openid_url"
			      open_id_authentication(params[:openid_url].strip)
			  elsif params[:email_addr]

		      user = User.authenticate(params[:email_addr], params[:password])
		      if user
		        session[:user_id] = user.id   
		        redirect_to(:controller => "index")
		      else
		        flash[:notice] = "Invalid user/password combination"
		      end
		     end
    end 
  end  
  

  
    protected



      def open_id_authentication(identity_url)    
           puts identity_url
          authenticate_with_open_id(identity_url, :required => [:nickname, :email], :optional => :fullname) do |status, identity_url, registration|
          puts "asdfasdf32453"
          case status
          when :missing
            failed_login "Sorry, the OpenID server couldn't be found"
          when :canceled
            failed_login "OpenID verification was canceled"
          when :failed
            failed_login "Sorry, the OpenID verification failed"
          when :successful
            if @current_user = @account.users.find_by_identity_url(identity_url)
              # registration is a hash containing the valid sreg keys given above
              # use this to map them to fields of your user model
              {'login=' => 'nickname', 'email=' => 'email', 'display_name=' => 'fullname'}.each do |attr, reg|
                current_user.send(attr, registration[reg]) unless registration[reg].blank?
              end
              unless current_user.save
                flash[:error] = "Error saving the fields from your OpenID profile: #{current_user.errors.full_messages.to_sentence}"
              end
              successful_login
            else
              failed_login "Sorry, no user by that identity URL exists"
            end
          end
        end  
    end

    
 
  



  private
  
    def successful_login
      session[:user_id] = @current_user.id 
      redirect_to(:controller => "index")
      flash[:notice] = "Logged in successfully"
    end

    def failed_login(message)
      redirect_to(:action => 'login')
      flash[:warning] = message
    end
  
end
